package com.unohacha.qqj.fzdr.personal.view.activity;

import android.content.Intent;
import android.support.design.widget.TabLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.qpg.widget.common.ToastUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.unohacha.qqj.fzdr.R;
import com.unohacha.qqj.fzdr.common.bean.HttpResult;
import com.unohacha.qqj.fzdr.common.bean.ReleaseBean;
import com.unohacha.qqj.fzdr.common.bean.ReleaseManagementBean;
import com.unohacha.qqj.fzdr.common.bean.ThreeLevelBean;
import com.unohacha.qqj.fzdr.common.bean.TwoLevelBean;
import com.unohacha.qqj.fzdr.common.http.RetrofitManager;
import com.unohacha.qqj.fzdr.personal.adapter.ReleaseAdapter;
import com.unohacha.qqj.fzdr.personal.view.IReleaseManagementView;
import com.unohacha.qqj.fzdr.ui.activity.PubManageDetialActivity;
import com.unohacha.qqj.fzdr.util.Prefer;
import com.unohacha.qqj.fzdr.util.ToastUtils;
import com.unohacha.qqj.fzdr.view.FlowLayout;
import com.unohacha.qqj.mylibrary.base.BaseActivity;
import com.zyyoona7.popup.EasyPopup;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 发布管理
 */
public class ReleaseManagementActivity extends BaseActivity implements IReleaseManagementView, OnRefreshListener, OnLoadmoreListener {

    private final static String TAG = "ReleaseManagement";
    @BindView(R.id.mRefreshLayout)
    SmartRefreshLayout mRefreshLayout;
//    @BindView(R.id.flowlayout)
//    FlowLayout flowlayout;

    //    private IReleaseManagementPresenter iReleaseManagementPresenter;
    private int page = 1;


    @BindView(R.id.common_back)
    ImageView commonBack;
    @BindView(R.id.common_title)
    RadioButton commonTitle;
    @BindView(R.id.common_title2)
    RadioButton commonTitle2;
    @BindView(R.id.common_right_image)
    ImageView rightImage;

    @BindView(R.id.rc_release_management)
    RecyclerView rcReleaseManagement;

    @OnClick(R.id.common_title)
    void onCommonTitleClick() {
        page = 1;
        firstLevel = "1";
        initDataRelease();
    }

    @OnClick(R.id.common_title2)
    void onCommonTitle2Click() {
        page = 1;
        firstLevel = "2";
        initDataRelease();
    }

    private List<TwoLevelBean> levelBeans;
    private String type="";

    // 保存供应/需求状态 1：供应 2：需求
    private String firstLevel = "1";

    // 二级标题
    @BindView(R.id.tb_two_level)
    TabLayout tbTwoLevel;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_release_management;
    }

    @OnClick(R.id.common_back)
    void onBackClick() {
        finish();
    }

    @OnClick(R.id.iv_level_more)
    void onLevelMoreClick() {
        int selected = tbTwoLevel.getSelectedTabPosition();
        List<ThreeLevelBean> threeLevelBeans = levelBeans.get(selected).getTwo();
        if (threeLevelBeans.size() > 0) {
            FlowLayout contentView = (FlowLayout) LayoutInflater.from(this).inflate(R.layout.flowlayout, null);

            for (ThreeLevelBean threeLevelBean : threeLevelBeans) {
                TextView tv = (TextView) mInflater.inflate(R.layout.item_textview, contentView, false);
                tv.setText(threeLevelBean.getName());
                final String txt = threeLevelBean.getId();
                tv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ToastUtils.showT(txt);
                        initDataRelease(txt);
                    }
                });
                contentView.addView(tv);
            }

            EasyPopup popWindow = EasyPopup.create()
                    .setContentView(contentView)
                    .setWidth(ViewGroup.LayoutParams.MATCH_PARENT)
                    //是否允许点击PopupWindow之外的地方消失
                    .setFocusAndOutsideEnable(true)
                    .apply();

            popWindow.showAsDropDown(tbTwoLevel);
        } else {
            ToastUtils.showT("没有数据");
        }
    }

    private List<ReleaseManagementBean> list;
    private ReleaseAdapter adapter;
    private LayoutInflater mInflater;

    @Override
    protected void initView() {
//        super.initView();
        setStatusBarColor(getResources().getColor(R.color.white));
        mRefreshLayout.setOnLoadmoreListener(this);
        mRefreshLayout.setOnRefreshListener(this);
        commonTitle.setText("供应发布");
        commonTitle2.setText("需求发布");
        mInflater = LayoutInflater.from(this);
        //创建布局管理
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rcReleaseManagement.setLayoutManager(layoutManager);
        list = new ArrayList<>();
        //创建适配器
        adapter = new ReleaseAdapter(R.layout.item_release, list);

        //给RecyclerView设置适配器
        rcReleaseManagement.setAdapter(adapter);
        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Intent intent=new Intent(ReleaseManagementActivity.this, PubManageDetialActivity.class);
                intent.putExtra("supply_cate_id",list.get(position).getSupply_cate_id());
                intent.putExtra("id",list.get(position).getId());
                intent.putExtra("label",type);
                startActivity(intent);
            }
        });
        // 加载二级标题
        initTwoLevel();
        // 添加监听
        tbTwoLevel.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                page = 1;
                type=tab.getText().toString();
                adapter.setLabel(tab.getText().toString());
                initDataRelease();
//                Toast.makeText(getApplicationContext(), "" + tbTwoLevel.getSelectedTabPosition() + "/"
//                        + levelBeans.get(tbTwoLevel.getSelectedTabPosition()).getName() + "/"
//                        + levelBeans.get(tbTwoLevel.getSelectedTabPosition()).getId(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        Log.i("token----------------->", Prefer.getInstance().getToken());
    }

    // 加载二级标题
    private void initTwoLevel() {
        
        showLoading();
        // 默认加载
        Call<HttpResult<List<TwoLevelBean>>> call = RetrofitManager.getInstance().supplyCate(Prefer.getInstance().getToken(),"2");
        call.enqueue(new Callback<HttpResult<List<TwoLevelBean>>>() {
            @Override
            public void onResponse(Call<HttpResult<List<TwoLevelBean>>> call, Response<HttpResult<List<TwoLevelBean>>> response) {
                
//                String data = response.body().getData().toString();
                if(response.body()!=null) {
                    if(response.body().getCode()==1) {
                        
                        List<TwoLevelBean> data = response.body().getData();
                        if (data != null) {
                            upDataTwoLevel(data);
                        } else {
                            Toast.makeText(getApplicationContext(), "获取失败", Toast.LENGTH_SHORT).show();
                        }
                    }
                }
                hideLoading();
            }

            @Override
            public void onFailure(Call<HttpResult<List<TwoLevelBean>>> call, Throwable t) {
                hideLoading();
            }
        });
    }

    // 更新二级标题
    private void upDataTwoLevel(List<TwoLevelBean> data) {
        
//        Log.d(TAG, "upDataTwoLevel: " + data.size());
        // 保存标题
        if (levelBeans == null) {
            levelBeans = new ArrayList<>();
        }
        levelBeans.clear();
        levelBeans.addAll(data);
//        Log.d(TAG, "onLevelMoreClick: " + Prefer.getInstance().getToken() + "/" + levelBeans.size());

        for (TwoLevelBean twoLevelBean : data) {
            tbTwoLevel.addTab(tbTwoLevel.newTab().setText(twoLevelBean.getName()));
        }
        initDataRelease();
    }

    // 加载发布数据
    private void initDataRelease() {
        // 测试数据
        showLoading();
        Log.d(TAG+"aaa", "onLevelMoreClick: " + Prefer.getInstance().getToken() + "/" + firstLevel + "/" + levelBeans.get(tbTwoLevel.getSelectedTabPosition()).getId() + "/" + page);
        Call<HttpResult<ReleaseBean>> call1 = RetrofitManager.getInstance()
                .supplyReleaseManagement(Prefer.getInstance().getToken(), firstLevel, levelBeans.get(tbTwoLevel.getSelectedTabPosition()).getId(), page);
        call1.enqueue(new Callback<HttpResult<ReleaseBean>>() {
            @Override
            public void onResponse(Call<HttpResult<ReleaseBean>> call, Response<HttpResult<ReleaseBean>> response) {
                if(response.code()==500){
                    hideLoading();
                    ToastUtil.showCustomToast("数据获取失败");
                    upDataRelease(new ReleaseBean());
                    return;
                }
                ReleaseBean data = response.body().getData();
                if (data != null) {
                    upDataRelease(data);
                } else if(data == null && page!=1){

                    closeRefresh();
                    hideLoading();
                    Toast.makeText(getApplicationContext(), "当前分类无数据", Toast.LENGTH_SHORT).show();
                }else if(data == null && page==1){
                    closeRefresh();
                    hideLoading();
                    Toast.makeText(getApplicationContext(), "当前分类无数据", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<HttpResult<ReleaseBean>> call, Throwable t) {
                closeRefresh();
            }
        });
    }

    // 加载发布数据
    private void initDataRelease(final String supply_cate_two) {
        // 测试数据
        showLoading();
        Log.d(TAG, "onLevelMoreClick: " + Prefer.getInstance().getToken() + "/" + firstLevel + "/" + levelBeans.get(0).getId() + "/" + page);
        Call<HttpResult<ReleaseBean>> call1 = RetrofitManager.getInstance()
                .supplyReleaseManagement(Prefer.getInstance().getToken(), firstLevel, levelBeans.get(tbTwoLevel.getSelectedTabPosition()).getId(), supply_cate_two, page);
        call1.enqueue(new Callback<HttpResult<ReleaseBean>>() {
            @Override
            public void onResponse(Call<HttpResult<ReleaseBean>> call, Response<HttpResult<ReleaseBean>> response) {
                ReleaseBean data = response.body().getData();
                if (data != null) {
                    upDataRelease(data);
                } else if(data == null && page!=1){

                    closeRefresh();
                    hideLoading();
                    Toast.makeText(getApplicationContext(), "当前分类无数据", Toast.LENGTH_SHORT).show();
                }else if(data == null && page==1){

                    closeRefresh();
                    hideLoading();
                    Toast.makeText(getApplicationContext(), "当前分类无数据", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<HttpResult<ReleaseBean>> call, Throwable t) {
                closeRefresh();
            }
        });
    }

    private void closeRefresh() {
        if (mRefreshLayout.isRefreshing()) {
            mRefreshLayout.finishRefresh();
        }
        if (mRefreshLayout.isLoading()) {
            mRefreshLayout.finishLoadmore();
        }
    }

//    private int page = 1;

    // 更新数据
    public void upDataRelease(ReleaseBean data) {
        Log.d(TAG, "upDataRelease: " + data);
//        Toast.makeText(getApplicationContext(), data.getTotal(), Toast.LENGTH_SHORT).show();
//        rcReleaseManagement.setAdapter(new ReleaseAdapter(R.layout.item_release, data.getData()));

        if (data.getData() == null) {
            Toast.makeText(getApplicationContext(), "当前分类无数据", Toast.LENGTH_SHORT).show();
            list.clear();
            adapter.notifyDataSetChanged();
        } else if (page == 1) {
            list.clear();
            list.addAll(data.getData());
            adapter.notifyDataSetChanged();
        } else {
            list.addAll(data.getData());
            adapter.notifyDataSetChanged();
        }
        closeRefresh();
        hideLoading();
    }

    @Override
    public void upReleaseManagementData(String data) {
        Log.d(TAG, "" + data);
    }

    @Override
    public void onLoadmore(RefreshLayout refreshlayout) {
        page++;
        initDataRelease();
    }

    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        page = 1;
        initDataRelease();
    }
}
